﻿using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace Core.Framework.CommonExceptions;

public class CommonExceptionFilter: IExceptionFilter
{
    public void OnException(ExceptionContext context)
    {
        var exception = context.Exception;

        if (exception is CommonException ex)
        {
            CommonExceptionResult result = new CommonExceptionResult();
            result.Code = (int)HttpStatusCode.InternalServerError;
            result.Data = null;
            result.Msg = ex.Msg;
            context.Result = new JsonResult(result);
        }
        else
        {
            CommonException commonException = new CommonException();
            commonException.Code = (int)HttpStatusCode.InternalServerError;
            commonException.Data = null;
            commonException.Msg = exception.Message;
            context.Exception = commonException;

            CommonExceptionResult commonExceptionResult = new CommonExceptionResult();
            commonExceptionResult.Code = (int)HttpStatusCode.InternalServerError;
            commonExceptionResult.Data = null;
            commonExceptionResult.Msg = exception.Message; //exception.Message;
            context.Result = new JsonResult(commonExceptionResult);
        }
    }
}